﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using RuoVea.ExUtil.Exceptions;
using SqlSugar;
using System.Data;
using RuoVea.Universal.Server.Language;

namespace RuoVea.Universal.Server.Service;
/// <summary>
/// 通用数据服务实现类
/// 提供数据上传、元数据初始化等通用数据操作功能
/// </summary>
[ApiExplorerSettings(GroupName = "RuoVea.Universal")]
public partial class UniversalService : IApplicationService
{
    private readonly ISqlSugarClient _defultDbContext;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="defultDbContext">数据库上下文</param>
    public UniversalService(ISqlSugarClient defultDbContext)
    {
        _defultDbContext = defultDbContext;
    }

    /// <summary>
    /// 初始化元数据表和数据（支持主从表）
    /// </summary>
    [HttpGet("InitMetadata/{tableName}")]
    public async Task InitMetadataData(string tableName, string[]? subTableNames = null, string? relationField = null)
    {
        try
        {
            if (!_defultDbContext.DbMaintenance.IsAnyTable(tableName))
                throw new ParamiterException(string.Format(i18n.table_not_exists, tableName));

            InitializeMetadataTables();

            var columns = _defultDbContext.DbMaintenance.GetColumnInfosByTableName(tableName);
            if (columns == null || columns.Count == 0)
                throw new ParamiterException(string.Format(i18n.cannot_get_column_info, tableName));

            var firstColumn = columns.FirstOrDefault();
            if (firstColumn == null)
                throw new ParamiterException(i18n.table_no_columns);

            // 修改：支持主从表配置
            var tableMetadata = CreateTableMetadata(firstColumn.TableName, subTableNames, relationField);

            // 修改：支持关联字段标记
            var fieldMetadatas = CreateFieldMetadatas(columns, tableMetadata.Id, relationField);

            await SaveMetadataToDatabase(tableMetadata, fieldMetadatas);
        }
        catch (Exception ex)
        {
            throw new ParamiterException(i18n.init_metadata_exception, ex);
        }
    }

    /// <summary>
    /// 原始表单行数据上传
    /// 直接根据表名上传单行数据
    /// </summary>
    /// <param name="tableName">目标表名称</param>
    /// <param name="dataStr">JSON格式的数据字符串</param>
    /// <returns>异步任务</returns>
    /// <exception cref="ParamiterException">当数据无效或验证失败时抛出</exception>
    [HttpPost("{tableName}/bytable")]
    public async Task ByTablePostData(string tableName, string dataStr)
    {
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new ParamiterException(i18n.no_upload_data);

        // 开启事务
        await _defultDbContext.Ado.BeginTranAsync();

        try
        {
            var data = ParseJsonData(dataStr);
            var columns = GetTableColumns(tableName);
            ValidateDataAgainstColumns(data, columns, tableName);

            await _defultDbContext.Insertable(data.ToObject<Dictionary<string, object>>())
                .AS(tableName)
                .ExecuteCommandAsync();

            // 提交事务
            await _defultDbContext.Ado.CommitTranAsync();
        }
        catch (Exception ex)
        {
            // 回滚事务
            await _defultDbContext.Ado.RollbackTranAsync();
            throw new ParamiterException(i18n.upload_failed_rollback, ex);
        }
    }


    /// <summary>
    /// 单行数据上传
    /// 根据主键类型标识上传单行数据
    /// </summary>
    /// <param name="primaryKeyType">主键类型标识</param>
    /// <param name="dataStr">JSON格式的数据字符串</param>
    /// <returns>异步任务</returns>
    /// <exception cref="ParamiterException">当数据无效或验证失败时抛出</exception>
    [HttpPost("{primaryKeyType}")]
    public async Task PostData(string primaryKeyType, string dataStr)
    {
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new ParamiterException(i18n.no_upload_data);

        // 开启事务
        await _defultDbContext.Ado.BeginTranAsync();

        try
        {
            var data = ParseJsonData(dataStr);
            var (tableMetadata, columns) = await GetTableMetadataAndColumns(primaryKeyType);
            ValidateAndProcessData(data, columns, 0);
            await ProcessDataByTransferType(data, tableMetadata, columns);

            // 提交事务
            await _defultDbContext.Ado.CommitTranAsync();
        }
        catch (Exception ex)
        {
            // 回滚事务
            await _defultDbContext.Ado.RollbackTranAsync();
            throw new ParamiterException(i18n.upload_failed_rollback, ex);
        }
    }

    /// <summary>
    /// 多数据批量上传
    /// 批量上传多行数据，支持大量数据高效处理
    /// </summary>
    /// <param name="primaryKeyType">主键类型标识</param>
    /// <param name="dataStr">JSON数组格式的数据字符串</param>
    /// <returns>异步任务</returns>
    /// <exception cref="ParamiterException">当数据无效或验证失败时抛出</exception>
    [HttpPost("{primaryKeyType}/bulk")]
    public async Task BulkPostData(string primaryKeyType, string dataStr)
    {
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new ParamiterException(i18n.no_upload_data);

        // 开启事务
        await _defultDbContext.Ado.BeginTranAsync();

        try
        {
            var dataArray = ParseJsonArrayData(dataStr);
            var (tableMetadata, columns) = await GetTableMetadataAndColumns(primaryKeyType);
            var processedData = new List<Dictionary<string, object>>();

            for (int i = 0; i < dataArray.Count; i++)
            {
                var dataItem = dataArray[i];
                ValidateAndProcessData(dataItem, columns, i + 1);
                processedData.Add(dataItem.ToObject<Dictionary<string, object>>()!);
            }

            await ProcessBulkDataByTransferType(processedData, tableMetadata, columns);

            // 提交事务
            await _defultDbContext.Ado.CommitTranAsync();
        }
        catch (Exception ex)
        {
            // 回滚事务
            await _defultDbContext.Ado.RollbackTranAsync();
            throw new ParamiterException(i18n.bulk_upload_failed_rollback, ex);
        }
    }

    /// <summary>
    /// 主从表数据上传（支持一主多从，包含完整事务处理）
    /// </summary>

    [HttpPost("{primaryKeyType}/masterdetail")]
    public async Task PostMasterDetailData(string primaryKeyType, string dataStr)
    {
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new ParamiterException(i18n.no_upload_data);

        // 开启事务
        await _defultDbContext.Ado.BeginTranAsync();

        try
        {
            var data = ParseJsonData(dataStr);

            // 获取主表元数据
            var masterTableMetadata = await _defultDbContext.Queryable<TableMetadata>()
                .Where(x => x.PrimaryKeyType == primaryKeyType)
                .FirstAsync();

            if (masterTableMetadata == null)
                throw new ParamiterException(string.Format(i18n.invalid_primary_key_type, primaryKeyType));

            // 获取主表字段信息
            var masterColumns = await _defultDbContext.Queryable<FieldMetadata>()
                .Where(x => x.TableMetaId == masterTableMetadata.Id)
                .ToListAsync();

            // 处理主表数据并获取主键ID
            var masterId = await ProcessMasterData(data, masterTableMetadata, masterColumns);

            // 处理从表数据
            await ProcessDetailTables(data, masterTableMetadata, masterId);

            // 提交事务
            await _defultDbContext.Ado.CommitTranAsync();
        }
        catch (Exception ex)
        {
            // 回滚事务
            await _defultDbContext.Ado.RollbackTranAsync();
            throw new ParamiterException(i18n.master_detail_upload_failed, ex);
        }
    }


    #region 私有辅助方法

    /// <summary>
    /// 初始化元数据表
    /// 确保TableMetadata和FieldMetadata表存在
    /// </summary>
    private void InitializeMetadataTables()
    {
        // 初始化表元数据表
        if (!_defultDbContext.DbMaintenance.IsAnyTable(nameof(TableMetadata)))
            _defultDbContext.CodeFirst.InitTables(typeof(TableMetadata));

        // 初始化字段元数据表
        if (!_defultDbContext.DbMaintenance.IsAnyTable(nameof(FieldMetadata)))
            _defultDbContext.CodeFirst.InitTables(typeof(FieldMetadata));
    }

    /// <summary>
    /// 创建表元数据对象
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="subTableNames"></param>
    /// <param name="relationField"></param>
    /// <returns></returns>
    private TableMetadata CreateTableMetadata(string tableName, string[]? subTableNames = null, string? relationField = null)
    {
        return new TableMetadata
        {
            TableName = tableName,
            PrimaryKeyType = tableName,
            TransferType = "Insert",
            // 修改：根据参数设置从表信息
            SubTableNames = subTableNames != null && subTableNames.Length > 0 ?
                string.Join(",", subTableNames) : "MasterData",
            RelationField = relationField,
            Id = IdGenerator.Id,
            CreateTime = DateTime.Now,
            ModifyTime = DateTime.Now,
            Deleted = RuoVea.ExEnum.IsDelete.N
        };
    }

    /// <summary>
    /// 创建字段元数据集合
    /// 根据数据库列信息生成字段元数据
    /// </summary>
    /// <param name="columns">数据库列信息集合</param>
    /// <param name="tableMetaId">表元数据ID</param>
    /// <param name="relationField"></param>
    /// <returns>字段元数据列表</returns>
    private List<FieldMetadata> CreateFieldMetadatas(List<DbColumnInfo> columns, long tableMetaId, string? relationField = null)
    {
        var systemProperties = typeof(IPrimaryKeyEntity).GetProperties()
            .Select(x => x.Name.ToLower())
            .ToList();

        var fieldMetadatas = new List<FieldMetadata>();

        foreach (var column in columns)
        {
            var fieldMetadata = new FieldMetadata
            {
                TableMetaId = tableMetaId,
                DbColumnName = column.DbColumnName,
                DataType = column.DataType,
                Length = column.Length,
                ColumnDescription = column.ColumnDescription,
                DefaultValue = column.DefaultValue,
                IsNullable = column.IsNullable,
                IsPrimarykey = column.IsPrimarykey,
                IsIdentity = column.IsIdentity,
                FieldSort = column.CreateTableFieldSort,
                IsSystemReserved = systemProperties.Contains(column.DbColumnName.ToLower()),
                ColumnAlias = column.DbColumnName,
                // 新增：标记关联字段
                IsRelationField = !string.IsNullOrEmpty(relationField) &&
                                 column.DbColumnName.Equals(relationField, StringComparison.OrdinalIgnoreCase),
                Id = IdGenerator.Id,
                CreateTime = DateTime.Now,
                ModifyTime = DateTime.Now,
                Deleted = RuoVea.ExEnum.IsDelete.N
            };

            fieldMetadatas.Add(fieldMetadata);
        }

        return fieldMetadatas;
    }
    #region 新增：主从表数据处理方法


    /// <summary>
    /// 处理主表数据
    /// </summary>
    private async Task<long> ProcessMasterData(JObject data, TableMetadata masterTable, List<FieldMetadata> masterColumns)
    {
        // 验证和处理主表数据
        ValidateAndProcessData(data, masterColumns);

        // 生成或获取主键ID
        long masterId;
        var idField = masterColumns.FirstOrDefault(x => x.IsPrimarykey);
        if (idField != null && data.ContainsKey(idField.DbColumnName) && data[idField.DbColumnName] != null)
        {
            masterId = data[idField.DbColumnName]!.ToObject<long>();
        }
        else
        {
            masterId = IdGenerator.Id;
            if (idField != null)
            {
                data[idField.DbColumnName] = masterId;
            }
        }

        // 根据TransferType处理主表数据
        var dataDict = data.ToObject<Dictionary<string, object>>();
        if (dataDict != null)
        {
            await ProcessDataByTransferTypeWithDict(dataDict, masterTable, masterColumns);
        }

        return masterId;
    }

    /// <summary>
    /// 处理从表数据
    /// </summary>
    private async Task ProcessDetailTables(JObject data, TableMetadata masterTable, long masterId)
    {
        // 检查是否配置了从表
        if (string.IsNullOrEmpty(masterTable.SubTableNames) ||
            masterTable.SubTableNames == "MasterData")
        {
            return; // 没有配置从表
        }

        var subTableNames = masterTable.SubTableNames.Split(',');

        foreach (var subTableName in subTableNames)
        {
            if (data.ContainsKey(subTableName))
            {
                await ProcessDetailTable(data[subTableName]!, subTableName, masterTable, masterId);
            }
        }
    }

    /// <summary>
    /// 处理单个从表数据
    /// </summary>
    private async Task ProcessDetailTable(JToken detailData, string tableName, TableMetadata masterTable, long masterId)
    {
        // 获取从表元数据
        var detailTableMetadata = await _defultDbContext.Queryable<TableMetadata>()
            .Where(x => x.TableName == tableName)
            .FirstAsync();

        if (detailTableMetadata == null)
        {
            throw new ParamiterException(string.Format(i18n.subtable_metadata_not_config, tableName));
        }

        // 获取从表字段信息
        var detailColumns = await _defultDbContext.Queryable<FieldMetadata>()
            .Where(x => x.TableMetaId == detailTableMetadata.Id)
            .ToListAsync();

        // 获取关联字段（优先使用从表配置的关联字段，如果没有则使用主表配置的）
        var relationField = !string.IsNullOrEmpty(detailTableMetadata.RelationField) ?
            detailTableMetadata.RelationField : masterTable.RelationField;

        if (string.IsNullOrEmpty(relationField))
        {
            throw new ParamiterException(string.Format(i18n.subtable_no_relation_field, tableName));
        }

        // 处理从表数据
        if (detailData is JArray detailArray)
        {
            foreach (var item in detailArray)
            {
                if (item is JObject detailItem)
                {
                    await ProcessDetailRow(detailItem, detailTableMetadata, detailColumns, relationField, masterId);
                }
            }
        }
        else if (detailData is JObject detailItem)
        {
            await ProcessDetailRow(detailItem, detailTableMetadata, detailColumns, relationField, masterId);
        }
    }


    /// <summary>
    /// 处理单行从表数据
    /// </summary>
    private async Task ProcessDetailRow(JObject detailItem, TableMetadata detailTable,
       List<FieldMetadata> detailColumns, string relationField, long masterId)
    {
        // 设置关联字段值
        detailItem[relationField] = masterId;

        // 验证和处理从表数据
        ValidateAndProcessData(detailItem, detailColumns);

        // 根据TransferType处理从表数据
        var dataDict = detailItem.ToObject<Dictionary<string, object>>();
        if (dataDict != null)
        {
            await ProcessDataByTransferTypeWithDict(dataDict, detailTable, detailColumns);
        }
    }
    /// <summary>
    /// 根据传输类型处理数据（Dictionary版本，用于主从表）
    /// </summary>
    private async Task ProcessDataByTransferTypeWithDict(Dictionary<string, object> dataDict,
        TableMetadata tableMetadata, List<FieldMetadata> columns)
    {
        switch (tableMetadata.TransferType)
        {
            case "Update":
                // 获取非系统保留的主键列
                var pkColumns = columns.Where(x => x.IsPrimarykey && !x.IsSystemReserved)
                    .Select(x => x.DbColumnName)
                    .ToArray();

                if (pkColumns.Length > 0)
                {
                    // 执行更新操作
                    await _defultDbContext.Storageable(dataDict)
                        .WhereColumns(pkColumns)
                        .As(tableMetadata.TableName)
                        .ExecuteCommandAsync();
                }
                else
                {
                    // 如果没有主键列，执行插入操作
                    await _defultDbContext.Insertable(dataDict)
                        .AS(tableMetadata.TableName)
                        .ExecuteCommandAsync();
                }
                break;

            case "Discard":
                // 检查数据是否已存在（丢弃模式）
                var exists = await CheckDataExists(dataDict, tableMetadata, columns);
                if (!exists)
                {
                    await _defultDbContext.Insertable(dataDict)
                        .AS(tableMetadata.TableName)
                        .ExecuteCommandAsync();
                }
                break;

            case "Insert":
                // 执行插入操作
                await _defultDbContext.Insertable(dataDict)
                    .AS(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            default:
                throw new ParamiterException(string.Format(i18n.unknown_transfer_type, tableMetadata.TransferType));
        }
    }

    /// <summary>
    /// 检查数据是否已存在（用于Discard模式）
    /// </summary>
    private async Task<bool> CheckDataExists(Dictionary<string, object> dataDict,
        TableMetadata tableMetadata, List<FieldMetadata> columns)
    {
        // 获取主键列
        var pkColumns = columns.Where(x => x.IsPrimarykey && !x.IsSystemReserved)
            .Select(x => x.DbColumnName)
            .ToArray();

        if (pkColumns.Length == 0)
            return false; // 没有主键列，总是插入

        // 构建查询条件
        var queryable = _defultDbContext.Queryable<object>().AS(tableMetadata.TableName);
        foreach (var pkColumn in pkColumns)
        {
            if (dataDict.ContainsKey(pkColumn) && dataDict[pkColumn] != null)
            {
                queryable = queryable.Where($"{"{"}0{"}"} = @pkValue", pkColumn, new { pkValue = dataDict[pkColumn] });
            }
            else
            {
                return false; // 主键值为空，插入新数据
            }
        }

        var exists = await queryable.CountAsync() > 0;
        return exists;
    }


    #endregion

    /// <summary>
    /// 保存元数据到数据库
    /// 使用事务确保数据一致性
    /// </summary>
    /// <param name="tableMetadata">表元数据</param>
    /// <param name="fieldMetadatas">字段元数据列表</param>
    /// <exception cref="ParamiterException">当保存失败时抛出</exception>
    private async Task SaveMetadataToDatabase(TableMetadata tableMetadata, List<FieldMetadata> fieldMetadatas)
    {
        try
        {
            // 开启事务
            await _defultDbContext.Ado.BeginTranAsync();

            // 插入表元数据
            await _defultDbContext.Insertable(tableMetadata).ExecuteCommandAsync();

            // 插入字段元数据
            await _defultDbContext.Insertable(fieldMetadatas).ExecuteCommandAsync();

            // 提交事务
            await _defultDbContext.Ado.CommitTranAsync();
        }
        catch (Exception ex)
        {
            // 回滚事务
            await _defultDbContext.Ado.RollbackTranAsync();
            throw new ParamiterException(i18n.init_metadata_exception, ex);
        }
    }

    /// <summary>
    /// 解析JSON数据字符串
    /// </summary>
    /// <param name="dataStr">JSON格式的字符串</param>
    /// <returns>JObject对象</returns>
    /// <exception cref="ParamiterException">当解析失败时抛出</exception>
    private JObject ParseJsonData(string dataStr)
    {
        var data = JsonConvert.DeserializeObject<JObject>(dataStr);
        if (data == null)
            throw new ParamiterException(i18n.no_valid_data);
        return data;
    }

    /// <summary>
    /// 解析JSON数组数据字符串
    /// </summary>
    /// <param name="dataStr">JSON数组格式的字符串</param>
    /// <returns>JObject列表</returns>
    /// <exception cref="ParamiterException">当解析失败时抛出</exception>
    private List<JObject> ParseJsonArrayData(string dataStr)
    {
        var dataArray = JsonConvert.DeserializeObject<List<JObject>>(dataStr);
        if (dataArray == null || dataArray.Count == 0)
            throw new ParamiterException(i18n.no_valid_data);
        return dataArray;
    }

    /// <summary>
    /// 获取表列信息
    /// </summary>
    /// <param name="tableName">表名称</param>
    /// <returns>列信息列表</returns>
    /// <exception cref="ParamiterException">当表不存在时抛出</exception>
    private List<DbColumnInfo> GetTableColumns(string tableName)
    {
        var columns = _defultDbContext.DbMaintenance.GetColumnInfosByTableName(tableName);
        if (columns == null || columns.Count == 0)
            throw new ParamiterException(string.Format(i18n.cannot_get_column_info, tableName));
        return columns;
    }

    /// <summary>
    /// 获取表元数据和字段信息
    /// </summary>
    /// <param name="primaryKeyType">主键类型标识</param>
    /// <returns>表元数据和字段信息元组</returns>
    /// <exception cref="ParamiterException">当元数据不存在时抛出</exception>
    private async Task<(TableMetadata, List<FieldMetadata>)> GetTableMetadataAndColumns(string primaryKeyType)
    {
        // 查询表元数据
        var tableMetadata = await _defultDbContext.Queryable<TableMetadata>()
            .Where(x => x.PrimaryKeyType == primaryKeyType)
            .FirstAsync();

        if (tableMetadata == null)
            throw new ParamiterException(string.Format(i18n.invalid_primary_key_type, primaryKeyType));

        // 查询字段元数据
        var columns = await _defultDbContext.Queryable<FieldMetadata>()
            .Where(x => x.TableMetaId == tableMetadata.Id)
            .ToListAsync();

        return (tableMetadata, columns);
    }

    /// <summary>
    /// 验证数据是否符合列定义
    /// 包括存在性、长度、类型等验证
    /// </summary>
    /// <param name="data">要验证的数据</param>
    /// <param name="columns">列定义集合</param>
    /// <param name="tableName">表名称（用于错误信息）</param>
    /// <exception cref="ParamiterException">当验证失败时抛出</exception>
    private void ValidateDataAgainstColumns(JObject data, List<DbColumnInfo> columns, string tableName)
    {
        foreach (var column in columns)
        {
            // 检查列是否存在
            if (!data.ContainsKey(column.DbColumnName))
                throw new ParamiterException(string.Format(i18n.column_missing, column.DbColumnName));

            var value = data[column.DbColumnName];
            if (value == null) continue;

            // 长度验证
            if (value.ToString().Length > column.Length)
                throw new ParamiterException(string.Format(i18n.value_length_exceeded, column.DbColumnName, column.Length));

            // 类型验证
            var dbType = DataDb.MapDbType(column.DataType);
            if (!DataDb.IsValueOfType(dbType, ref value))
                throw new ParamiterException(string.Format(i18n.column_missing, column.DbColumnName, dbType));
        }
    }

    /// <summary>
    /// 验证和处理数据
    /// 包括系统值设置、主键验证、必填验证、类型验证等
    /// </summary>
    /// <param name="data">要处理的数据</param>
    /// <param name="columns">字段元数据集合</param>
    /// <param name="rowIndex">行索引（用于错误信息）</param>
    /// <exception cref="ParamiterException">当验证失败时抛出</exception>
    private void ValidateAndProcessData(JObject data, List<FieldMetadata> columns, int rowIndex = 0)
    {
        string rowPrefix = rowIndex > 0 ? string.Format(i18n.rowIndex, rowIndex) : "";

        foreach (var column in columns)
        {
            // 设置系统保留值（如创建时间、修改时间等）
            if (DataDb.SetReservedValue(column.DbColumnName, out JToken? resValue))
            {
                data[column.DbColumnName] = resValue!;
                continue;
            }

            // 主键验证
            if (column.IsPrimarykey && !data.ContainsKey(column.DbColumnName))
                throw new ParamiterException(rowPrefix + string.Format(i18n.primary_key_missing, column.DbColumnName));

            // 必填字段验证
            if (!column.IsNullable && (!data.ContainsKey(column.DbColumnName) ||
                data[column.DbColumnName] == null ||
                string.IsNullOrWhiteSpace(data[column.DbColumnName]!.ToString())))
            {
                throw new ParamiterException(rowPrefix + string.Format(i18n.required_column_empty, column.DbColumnName));
            }

            // 如果列不存在，跳过后续验证
            if (!data.ContainsKey(column.DbColumnName))
                continue;

            var value = data[column.DbColumnName]!;

            // 长度验证
            if (value.ToString().Length > column.Length)
                throw new ParamiterException(rowPrefix + string.Format(i18n.value_length_exceeded, column.DbColumnName, column.Length));

            // 类型验证
            var dbType = DataDb.MapDbType(column.DataType);
            if (!DataDb.IsValueOfType(dbType, ref value))
                throw new ParamiterException(rowPrefix + string.Format(i18n.column_missing, column.DbColumnName, dbType));

            // 特殊类型处理（如日期时间）
            if (dbType == System.Data.DbType.DateTime)
                data[column.DbColumnName] = value;
        }
    }

    /// <summary>
    /// 根据传输类型处理数据
    /// 支持插入、更新、丢弃三种操作类型
    /// </summary>
    /// <param name="data">要处理的数据</param>
    /// <param name="tableMetadata">表元数据</param>
    /// <param name="columns">字段元数据集合</param>
    /// <returns>异步任务</returns>
    /// <exception cref="ParamiterException">当传输类型未知时抛出</exception>
    private async Task ProcessDataByTransferType(JObject data, TableMetadata tableMetadata, List<FieldMetadata> columns)
    {
        var dataDict = data.ToObject<Dictionary<string, object>>();
        if (dataDict == null) return;

        switch (tableMetadata.TransferType)
        {
            case "Update":
                // 获取非系统保留的主键列
                var pkColumns = columns.Where(x => x.IsPrimarykey && !x.IsSystemReserved)
                    .Select(x => x.DbColumnName)
                    .ToArray();

                // 执行更新操作
                await _defultDbContext.Storageable(dataDict)
                    .WhereColumns(pkColumns)
                    .As(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            case "Discard":
                // 执行插入操作（丢弃模式）
                await _defultDbContext.Insertable(dataDict)
                    .AS(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            case "Insert":
                // 执行插入操作
                await _defultDbContext.Insertable(dataDict)
                    .AS(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            default:
                throw new ParamiterException(string.Format(i18n.unknown_transfer_type, tableMetadata.TransferType));
        }
    }

    /// <summary>
    /// 批量处理数据根据传输类型
    /// 支持批量插入、更新操作
    /// </summary>
    /// <param name="dataList">数据列表</param>
    /// <param name="tableMetadata">表元数据</param>
    /// <param name="columns">字段元数据集合</param>
    /// <returns>异步任务</returns>
    /// <exception cref="ParamiterException">当传输类型未知时抛出</exception>
    private async Task ProcessBulkDataByTransferType(List<Dictionary<string, object>> dataList,
        TableMetadata tableMetadata, List<FieldMetadata> columns)
    {
        switch (tableMetadata.TransferType)
        {
            case "Update":
                // 获取非系统保留的主键列
                var pkColumns = columns.Where(x => x.IsPrimarykey && !x.IsSystemReserved)
                    .Select(x => x.DbColumnName)
                    .ToArray();

                // 执行批量更新操作
                await _defultDbContext.Storageable(dataList)
                    .WhereColumns(pkColumns)
                    .As(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            case "Discard":
            case "Insert":
                // 执行批量插入操作
                await _defultDbContext.Insertable(dataList)
                    .AS(tableMetadata.TableName)
                    .ExecuteCommandAsync();
                break;

            default:
                throw new ParamiterException(string.Format(i18n.unknown_transfer_type, tableMetadata.TransferType));
        }
    }

    #endregion
}